package com.zimmur.tools;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 根据IP查询所属国家
 * @author Administrator
 *
 */
public class IPDataHandler {
	private Logger log = LoggerFactory.getLogger(IPDataHandler.class);
	
	//访问新浪接口，获取ip和地理位置信息
	 //返回数据格式：1 121.15.0.0121.15.215.255 中国 广东 深圳 电信
	public String getCurrentProvinceAndCity(String ip) {
		String result = "";	
		String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";
		try {
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("ip", ip));
			String mResult = HttpClientUtil.doGet(url, params);

			if (mResult != null && !mResult.equals("")) {
				String[] results = mResult.split("\t");
				if (results.length >= 4) {
					result = results[3];
				}
			}
		} catch (Exception e) {
			result = "";
			log.error(e.getMessage());
		}
		return result;
	}
	  
	
	public static void main(String[] args) {
		IPDataHandler ipDataHandler = new IPDataHandler();
		String strLocation = ipDataHandler.getCurrentProvinceAndCity("28.75.42.65");
		System.out.println(strLocation);
	}
}
